package com.sinsz.pay.factory.support;

import com.alipay.api.AlipayClient;
import com.sinsz.pay.exception.PayException;
import org.nutz.http.Request;
import org.nutz.http.Response;
import org.nutz.http.Sender;

import javax.net.ssl.SSLSocketFactory;

/**
 * 微信证书或支付宝请求实例
 * @author chenjianbo
 */
public class SSLConstant {

    private static final SSLConstant SSL_CONSTANT = new SSLConstant();

    private SSLConstant() {
    }

    public static SSLConstant instance() {
        return SSL_CONSTANT;
    }

    /**
     * 微信支付的证书工厂
     */
    private SSLSocketFactory wxSslSocketFactory;

    /**
     * 设置微信支付证书工厂
     * @param wxSslSocketFactory
     */
    public void setWxSslSocketFactory(SSLSocketFactory wxSslSocketFactory) {
        this.wxSslSocketFactory = wxSslSocketFactory;
    }

    /**
     * 微信支付带证书请求扩展
     * @param url       请求地址
     * @param xml       xml参数
     * @param timeout   请求超时时间
     * @return          请求返回对象
     */
    public Response postWxPay(String url, String xml, int timeout) {
        Request req = Request.create(url, Request.METHOD.POST);
        req.setData(xml);
        req.getHeader().set("Content-Type", "application/xml");
        if (wxSslSocketFactory == null) {
            throw new PayException("微信支付证书加载错误.");
        }
        return Sender.create(req).setSSLSocketFactory(wxSslSocketFactory).setTimeout(timeout).send();
    }

    /**
     * 支付宝支付请求客户端
     */
    private AlipayClient alipayClient;

    /**
     * 初始化设置赋值
     * @param alipayClient
     */
    public void setAlipayClient(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    /**
     * 取得支付请求客户端
     * @return
     */
    public AlipayClient alipayClient() {
        if (alipayClient == null) {
            throw new PayException("支付宝支付客户端初始化失败.");
        }
        return alipayClient;
    }
}
